package com.weixing.mall.provider.auth.member;

import com.alibaba.fastjson.JSON;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.provider.enums.LoginEnum;
import com.weixing.oauth2.common.constants.SecurityConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @ClassName SysUserAuthController
 * @Description 短信验证码过滤器
 * @Author Small
 * @Date 2019/12/25 14:45
 * @Version 1.0
 **/
@Component("smsCodeFilter")
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean {


	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	public SmsCodeFilter(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
		String requestURL = httpServletRequest.getRequestURI();
		if (requestURL.equals(LoginEnum.MEMBER_SMS_CODE.getValue())){
			String key = GlobalConstant.REDIS_PRE_SMS + httpServletRequest.getParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE);
			String verifyCode_redis = stringRedisTemplate.opsForValue().get(key);
			String verifyCode = httpServletRequest.getParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS);
			httpServletResponse.setContentType("application/json;charset=UTF-8");
			if (StringUtils.isBlank(verifyCode_redis)){
				logger.info("验证码已过期");
				httpServletResponse.getWriter().write(JSON.toJSONString(ResultUtil.error(ResultCodeEnum.CODE_10011004)));
				return;
			}
			if (verifyCode.equalsIgnoreCase(verifyCode_redis)){
				logger.info("验证码校验通过");
			}else{
				System.out.println("短信验证码验证失败");
				httpServletResponse.getWriter().write(JSON.toJSONString(ResultUtil.error(ResultCodeEnum.CODE_10011005)));
				return;
			}
		}
		filterChain.doFilter(httpServletRequest, httpServletResponse);
	}
}
